////////////////////////////////////////////////////////////////////////////////
//  COPYRIGHT (C) 2010 TELECOM DIGITAL MEDIA ("TDMEDIA").
//  ALL RIGHTS RESERVED.
//
//  THIS IS CONFIDENTIAL AND PROPRIETARY INTELLECTUAL PROPERTY OWNED BY AND
//  CREATED ON BEHALF OF TDMEDIA. ANY FORM OF DISTRIBUTION, COPY,
//  MODIFICATION WITHOUT THE WRITTEN CONSENT FROM TDMEDIA IS STRICTLY
//  PROHIBITED.
////////////////////////////////////////////////////////////////////////////////
package cc.telecomdigital.tdstock.activity.groups.monitor;

import java.util.ArrayList;
import java.util.List;

import android.R.color;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import cc.telecomdigital.tdstock.BaseAsyncTask;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Http.H_CODE;
import cc.telecomdigital.tdstock.Http.HttpSuperClassStockBaseActivity;
import cc.telecomdigital.tdstock.Http.Services.HttpAppInfo;
import cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.H_UserClient_HttpRequest_Result;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.groups.MonitorGroup;
import cc.telecomdigital.tdstock.activity.groups.MoreGroup;
import cc.telecomdigital.tdstock.activity.groups.more.FinetListItemContentActivity;
import cc.telecomdigital.tdstock.adapter.NewsListItemAdapter;
import cc.telecomdigital.tdstock.adapter.NewsViewHolder;

/**
 * 
 * @author haibo
 * 
 *  for  searching on stock by name or code
 *
 */
public class MonitorNewsFActivity extends HttpSuperClassStockBaseActivity
{
	protected static final String		TAG			= MonitorNewsFActivity.class.getSimpleName();

	private Button						_btnLeft;
	private Button						_btnRight;
	private Button						_btn1;
	private Button						_btn2;
	private Button						_btn3;
	private Button						_btn4;
	private Button						_btn5;
	private Button						_btn6;
	private Button						_btn7;
	private Button						_btn8;

	private HorizontalScrollView		_scrollBar;
	private Button						_toolBtnReturn;

	private static String				_catId;
	private static String				_vendorId;

	private static final long			SPECIAL_ID_LOAD_NEXT			= 80000l;
	private static final long			SPECIAL_ID_LOAD_EOF				= 70000l;
	private static final long			SPECIAL_ID_LOAD_NONE			= 60000l;
	private static final long			START_ID						= 90000l;

	private ListView					_listView;

	private TextView					_topBar;

	private String[]					_tabCaptionList;
	private String[]					_catIdList;

	private String[]					_newsTitleList;	
	private String[]					_newsIdList;

	private static NewsListItemAdapter	_newsAdapter;
	private static List<NewsViewHolder>	_newsList;
	private String[]					_timestamp;  

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.monitor_news_f);

		_topBar = (TextView) findViewById(R.id.top_bar_title);

		_toolBtnReturn = (Button) findViewById(R.id.more_returnbtn);
		_toolBtnReturn.setFocusable(true);
		_toolBtnReturn.setClickable(true);
		_toolBtnReturn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				TDStockLog.d(TAG, "close current activity and forwarding to the previous");

				// BMP Mode by ouyangzhihui 2011-10-13
				Class<? extends Activity> _cls = PortfolioActivity.class;
				if(((ITDLApplication)getApplicationContext()).getIsBMPMode())
				{
					_cls = BMPPortfolioActivity.class;
				}
				
				Intent intent = new Intent(getApplicationContext(), _cls);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				SwitchForwardActivity(_cls, intent);
			}

		});

		initTabBar();

		_listView = (ListView) findViewById(R.id.more_news_list);
		_newsList = new ArrayList<NewsViewHolder>();
		_newsAdapter = new NewsListItemAdapter(LayoutInflater.from(this),
				_newsList);
		_listView.setAdapter(_newsAdapter);
	}

	private void initTabBar()
	{
		_btnLeft = (Button) findViewById(R.id.btn_left);
		_btnRight = (Button) findViewById(R.id.btn_right);

		_btnLeft.setVisibility(View.INVISIBLE);
		_btnRight.setVisibility(View.VISIBLE);

		_btn1 = (Button) findViewById(R.id.btn1);
		_btn2 = (Button) findViewById(R.id.btn2);
		_btn3 = (Button) findViewById(R.id.btn3);
		_btn4 = (Button) findViewById(R.id.btn4);
		_btn5 = (Button) findViewById(R.id.btn5);
		_btn6 = (Button) findViewById(R.id.btn6);
		_btn7 = (Button) findViewById(R.id.btn7);
		_btn8 = (Button) findViewById(R.id.btn8);

		OnFocusChangeListener focus = new OnFocusChangeListener()
		{
			@Override
			public void onFocusChange(View v, boolean hasFocus)
			{
				v.setBackgroundResource(hasFocus ? R.drawable.news_bg_selected : color.transparent);

				int position = 0;
				if (v == _btn1)
				{
					position = 0;
					_topBar.setText(getResources().getString(
							R.string.monitor_news_f)
							+ "-" + _btn1.getText().toString());
				}
				else if (v == _btn2)
				{
					_topBar.setText(getResources().getString(
							R.string.monitor_news_f)
							+ "-" + _btn2.getText().toString());
					position = 1;
				}
				else if (v == _btn3)
				{
					_topBar.setText(getResources().getString(
							R.string.monitor_news_f)
							+ "-" + _btn3.getText().toString());
					position = 2;
				}
				else if (v == _btn4)
				{
					_topBar.setText(getResources().getString(
							R.string.monitor_news_f)
							+ "-" + _btn4.getText().toString());
					position = 3;
				}
				else if (v == _btn5)
				{
					_topBar.setText(getResources().getString(
							R.string.monitor_news_f)
							+ "-" + _btn5.getText().toString());
					position = 4;
				}
				else if (v == _btn6)
				{
					_topBar.setText(getResources().getString(
							R.string.monitor_news_f)
							+ "-" + _btn6.getText().toString());
					position = 5;
				}
				else if (v == _btn7)
				{
					_topBar.setText(getResources().getString(
							R.string.monitor_news_f)
							+ "-" + _btn7.getText().toString());
					position = 6;
				}
				else if (v == _btn8)
				{
					_topBar.setText(getResources().getString(
							R.string.monitor_news_f)
							+ "-" + _btn8.getText().toString());
					position = 7;
				}
				// modify by zor(ouyangzhihui) --start
				if (v == _btn1)
				{
					_btnLeft.setVisibility(View.INVISIBLE);
					_btnRight.setVisibility(View.VISIBLE);
				}
				else if (v == _btn8)
				{
					_btnLeft.setVisibility(View.VISIBLE);
					_btnRight.setVisibility(View.INVISIBLE);
				}
				else
				{
					_btnLeft.setVisibility(View.VISIBLE);
					_btnRight.setVisibility(View.VISIBLE);
				}
				// modify by zor(ouyangzhihui) --end

//				_vendorId = NewsCategoriesParser.FILTER_TAG_VALUE.toLowerCase();
				_vendorId = "f";
				if (_catIdList == null || _catIdList.length < position + 1)
				{
					return;
				}
				_catId = _catIdList[position];
				if (hasFocus)
				{

					_newsList.clear();
					_timestamp = null;
					_newsTitleList = null;
					_newsIdList = null;
					_newsAdapter.notifyDataSetChanged();

					iIsNextMore = false;
					SendHttpRequest();
				}
			}
		};

		_btn1.setOnFocusChangeListener(focus);
		_btn2.setOnFocusChangeListener(focus);
		_btn3.setOnFocusChangeListener(focus);
		_btn4.setOnFocusChangeListener(focus);
		_btn5.setOnFocusChangeListener(focus);
		_btn6.setOnFocusChangeListener(focus);
		_btn7.setOnFocusChangeListener(focus);
		_btn8.setOnFocusChangeListener(focus);

		_scrollBar = (HorizontalScrollView) findViewById(R.id.scrolling_bar);

		_scrollBar.setOnTouchListener(new OnTouchListener()
		{

			@Override
			public boolean onTouch(View v, MotionEvent event)
			{
				resetNaviBtn();
				return false;
			}

		});

		_btnLeft.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				_scrollBar.arrowScroll(View.FOCUS_LEFT);
				if (_btn1.isFocused())
				{
					_btnLeft.setVisibility(View.INVISIBLE);
					_btnRight.setVisibility(View.VISIBLE);
				}
			}
		});

		_btnRight.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				_scrollBar.arrowScroll(View.FOCUS_RIGHT);
				//resetNaviBtn();
				if (_btn8.isFocused())
				{
					_btnLeft.setVisibility(View.VISIBLE);
					_btnRight.setVisibility(View.INVISIBLE);
				}
			}
		});
	}

	@Override
	protected void onResume()
	{
		SetExectuHttpRequestOnResume(false);
		
		super.onResume();

		if (_tabCaptionList == null || _tabCaptionList.length < 3)
		{
			new FetchNewsCategories(getMyOwnContext()).execute(); //just execute once;
		}
		_listView.invalidateViews();
	}

	private class FetchNewsCategories extends BaseAsyncTask
	{
		public FetchNewsCategories(Context context)
		{
			super(context);
		}

		@Override
		protected Void doInBackground(String... params)
		{
			_tabCaptionList = new String[] { "市場新聞", "公司業績", "外圍消息", "外匯新聞", "藍籌動向", "地產新聞", "紅籌國企", "新股上市" };
			_catIdList = new String[] { "1", "2", "3", "4", "5", "6", "7", "8" };
			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			super.onPostExecute(result);
			updateTabButtons();
		}
	}


	private void updateAdapter()
	{
		if (!_newsList.isEmpty())
		{
			_newsList.remove(_newsList.size() - 1); //remove the last item for it just a flag mark the news list.
		}

		long id = START_ID + _newsList.size();
		for (int index = 0, listSize = _newsTitleList == null ? 0
				: _newsTitleList.length; index < listSize; index++)
		{
			id += index;
			NewsViewHolder viewHolder = new NewsViewHolder();
			viewHolder.id = id;
			viewHolder.newsId = _newsIdList[index];
			viewHolder.text = new TextView(this);
			viewHolder.text.setText(_newsTitleList[index]);
			viewHolder.sign = new ImageView(this);
			_newsList.add(viewHolder);
		}

		int theLastItemResouceId = 0;
		if (_newsTitleList == null || _newsTitleList.length < 1
				|| _newsList.size() < 1)
		{
			id = SPECIAL_ID_LOAD_NONE;
			theLastItemResouceId = R.string.provide_no_information; // modify by zor(ouyangzhihui)
		}
		else if (_newsTitleList.length == 20)
		{
			id = SPECIAL_ID_LOAD_NEXT;
			theLastItemResouceId = R.string.record_tips_next;
		}
		else if (_newsTitleList.length < 20)
		{
			id = SPECIAL_ID_LOAD_EOF;
			theLastItemResouceId = R.string.record_tips_eof;
		}

		//-----create the last item as the mark of the news---------------
		NewsViewHolder viewHolder = new NewsViewHolder();
		viewHolder.id = id;
		viewHolder.text = new TextView(this);
		viewHolder.text.setText(theLastItemResouceId);
		viewHolder.sign = new ImageView(this);
		_newsList.add(viewHolder);
		//-----create the last item as the mark of the news---------------

		_listView.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id)
			{
				if (position != -1)
				{
					if (id == SPECIAL_ID_LOAD_NEXT)
					{
						// list load more
						iIsNextMore = true;
						SendHttpRequest();
					}
					else if (id == SPECIAL_ID_LOAD_EOF || id == SPECIAL_ID_LOAD_NONE)
					{
						//do nothing
					}
					else
					{
						FinetListItemContentActivity._iId = _newsList.get(position).newsId;
						FinetListItemContentActivity._iVendor = _vendorId;
						
						FinetListItemContentActivity._btnCaption = _topBar.getText().toString();

						FinetListItemContentActivity._fromActivityClass = MonitorNewsFActivity.class;
						Intent intent = new Intent(MonitorNewsFActivity.this, FinetListItemContentActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
						SwitchForwardActivity(FinetListItemContentActivity.class, intent);
					}
				}
			}
		});

		if (_listView.getAdapter() == null
				|| _listView.getAdapter().getCount() < 1)
		{
			_newsAdapter = new NewsListItemAdapter(
					LayoutInflater.from(this), _newsList);
			_listView.setAdapter(_newsAdapter);
		}
		else
		{
			_newsAdapter.notifyDataSetChanged();
		}

	}

//	private void updateLocalData()
//	{
//		if (!_newsList.isEmpty())
//		{
//			_newsList.clear();
//		}
//		if (_items == null)
//		{
//			return;
//		}
//		int length = _items.size();
//		_tabCaptionList = new String[length];
//		_catIdList = new String[length];
//		_timestamp = new String[length];
//		int item = 0;
//		for (String[] array : _items)
//		{
//			_tabCaptionList[item] = String.format("%s  %s ", array[1]
//					.substring(0, 16), array[2]);
//			_catIdList[item] = array[0];
//			_timestamp[item] = array[1];
//			item++;
//		}
//
//		//_category_name.setText(_title);
//		TDStockLog.d(TAG, "Title=" + (_title == null ? "" : _title));
//		//_category_name.postInvalidate();
//	}

	private void updateTabButtons()
	{
		if (_tabCaptionList != null && _tabCaptionList.length >= 8)
		{
			_btn1.setText(_tabCaptionList[0]);
			_btn2.setText(_tabCaptionList[1]);
			_btn3.setText(_tabCaptionList[2]);
			_btn4.setText(_tabCaptionList[3]);
			_btn5.setText(_tabCaptionList[4]);
			_btn6.setText(_tabCaptionList[5]);
			_btn7.setText(_tabCaptionList[6]);
			_btn8.setText(_tabCaptionList[7]);

			_btn1.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					_btnLeft.setVisibility(View.INVISIBLE);
				}
			});

			_btn8.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					_btnRight.setVisibility(View.INVISIBLE);
				}
			});

			_btn1.requestFocus();
		}
		else
		{
			_btn1.setText("");
			_btn2.setText("");
			_btn3.setText("");
			_btn4.setText("");
			_btn5.setText("");
			_btn6.setText("");
			_btn7.setText("");
			_btn8.setText("");
		}
	}

	private void resetNaviBtn()
	{
		final int btn_number = 8;
		final Runnable job = new Runnable()
		{
			@Override
			public void run()
			{
				TDStockLog.d(TAG, "->ScollX:" + _scrollBar.getScrollX());
				TDStockLog.d(TAG, "->getMeasuredWidth:"
						+ _scrollBar.getMeasuredWidth());
				TDStockLog.d(TAG, "->_screenWidth:" + _display.getWidth());
				TDStockLog.d(TAG, "-> button1's width:" + _btn1.getWidth());
				TDStockLog.d(TAG, "->button1's MeasuredWidth:"
						+ _btn1.getMeasuredWidth());
				TDStockLog.d(TAG, "-> button8's width:" + _btn8.getWidth());
				TDStockLog.d(TAG, "->button8's MeasuredWidth:"
						+ _btn8.getMeasuredWidth());

				TDStockLog.d(TAG, "-> button5's width:" + _btn5.getWidth());
				TDStockLog.d(TAG, "->button5's MeasuredWidth:"
						+ _btn5.getMeasuredWidth());
				_btnLeft
						.setVisibility(_scrollBar.getScrollX() >= btn_number ? View.VISIBLE
								: View.INVISIBLE);
				_btnRight.setVisibility(_scrollBar.getScrollX() <= _btn1
						.getWidth()
						* btn_number - _display.getWidth() ? View.VISIBLE
						: View.INVISIBLE);
			}
		};

		new Thread()
		{
			@Override
			public void run()
			{
				//handler.post(job);
				if (_messageHandler != null)
					_messageHandler.postDelayed(job, 300);
			}
		}.start();
	}

	@Override
	public ActivityGroupController GetActivityGroupController()
	{
		//share the same tab with  more group,
		return MonitorGroup.GetActivityGroupHostControl() == null ?  MoreGroup.GetActivityGroupHostControl() : MonitorGroup.GetActivityGroupHostControl() ;
	}

	private boolean iIsNextMore = false;
	
	@Override
	protected H_CODE GetDataFromHttpServer()
	{
		if(_vendorId == null || _catId == null)
			return null;
		
		if(iIsNextMore)
		{
			String[] timeParams = HttpAppInfo.GetDataTimeParams(_timestamp, false);
			
			return HttpAppInfo.SendDjFNewsListRequest(actContext, _vendorId, _catId, timeParams[0], timeParams[1], this);
		}
		else
		{
			return HttpAppInfo.SendDjFNewsListRequest(actContext, _vendorId, _catId, this);
		}
	}

	@Override
	protected void H_UserClient_HttpRequest_Response_Sub(final H_UserClient_HttpRequest_Result iResult)
	{
		if (!iResult.MStatus.equals("0"))
		{
			iIsNextMore = false;
			ShowMessageDialog(iResult.MError + "(" + iResult.MStatus + ")");
			return;
		}
		
		int count = iResult.contentStores.size();
		
		TDStockLog.d(TAG, "Count="+count);
		
		Runnable runnable = new Runnable()
		{
			@Override
			public void run()
			{
				updateData(iResult.contentStores);
				updateAdapter();
			}
		};
		_messageHandler.post(runnable);
	}

	private void updateData(List<String[]> _list)
	{
		if(!iIsNextMore)
		{
			iIsNextMore = false;
			_newsList.clear();
			_timestamp = null;
		}
		
		if (_list == null || _list.isEmpty())
		{
			return;
		}
		int length = _list.size();
		_newsTitleList = new String[length];
		_newsIdList = new String[length];
		_timestamp = new String[length];
		int item = 0;
		for (String[] array : _list)
		{
			_newsTitleList[item] = String.format("%s  %s ", array[1].substring(0, 16), array[2]);
			_newsIdList[item] = array[0];
			_timestamp[item] = array[1]; //updated in the  new page
			item++;
		}
	}
}
